package com.yuan.work_rr.recv;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

/**
 * @Author 小源同学
 * @Date 2022 02 05 13 25
 * @Describe 【工作队列_轮询】：消息消费者1
 **/
public class Recv01 {
    //队列名称
    private final static String QUEUE_NAME = "work_rr";

    public static void main(String[] argv) throws Exception {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //填写rabbitmq所在机器的ip地址
        factory.setHost("localhost");
        factory.setUsername("spm");
        factory.setVirtualHost("/spm");
        factory.setPassword("123");
        factory.setPort(5672);
        //创建连接
        Connection connection = factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        /*
            consumerTag 消费者的标签
            delivery 获取到的对应的消息
         */
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            //模拟消耗耗时
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
            //手动确认
            //multiple最后的布尔值是：是否多选
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        };
        //监听队列消费信息
        /*
            第一个参数：队列的名称
            第二个参数：自动回值，告诉队列我收到消息了【可能导致收不到消息，防止二次处理】

         */
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
        });
    }
}
